<template>
  <a-upload-dragger
    name="file"
    :showUploadList="false"
    :before-upload="beforeUpload"
  >
    <template v-if="!file">
      <slot />
    </template>
    <template v-else>
      <img class="image_area" :src="file.preview" />
    </template>
  </a-upload-dragger>
</template>

<script>
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = (error) => reject(error);
  });
}
export default {
  data() {
    return {
      file: undefined,
      fileTypeList: ["image/png", "image/jpeg"],
    };
  },
  methods: {
    beforeUpload(file) {
      if (this.fileTypeList.indexOf(file.type) > -1) {
        this.getFileUrl(file);
      } else {
        this.$toast.fail("请注意，需要上传图片格式的文件");
      }
      return false;
    },

    async getFileUrl(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file);
      }
      this.file = file;
      this.$emit("getFile", file);
    },
  },
};
</script>

<style lang="less" scoped>
.image_area {
  width: 300px;
  height: 300px;
}
</style>
